require "pathname"
require "cgi"

# load the openid library
begin
  require "rubygems"
  require_gem "ruby-openid", ">= 2.0.3"
rescue LoadError
  require "openid"
end

class AccountController < ApplicationController
  layout  'default'

  def index
    @pages, @items = paginate(:item, :per_page => 2, :order_by => 'gift_counts desc')
  end

  # process the login request, disover the openid server, and
  # then redirect.
  def login
    openid_url = params[:openid_url]
    if request.post?
      begin
        request = consumer.begin(openid_url)
        return_to = url_for(:action=> 'complete')
        trust_root = url_for(:controller=>'')

        url = request.redirect_url(trust_root, return_to)
        redirect_to(url)

      rescue OpenID::OpenIDError
        flash[:notice] = 'Authorization failed.'

      end
    end
  end

  # handle the openid server response
  def complete
    current_url = url_for(:action => 'complete', :only_path => false)
    parameters = params.reject{|k,v|request.path_parameters[k]}
    response = consumer.complete(parameters, current_url)

    case response.status
    when OpenID::Consumer::SUCCESS

      @user = User.get(response.identity_url)

      # create user object if one does not exist
      if @user.nil?
        @user = User.new(:openid_url => response.identity_url)
        @user.save
      end

      # storing both the openid_url and user id in the session for for quick
      # access to both bits of information.  Change as needed.
      @session[:user_id] = @user.id
      @session[:user_uri] = response.identity_url
      flash[:notice] = "Logged in as #{CGI::escape(response.identity_url)}"
      if @session[:back_url]
        url = @session[:back_url]
        @session[:back_url] = nil
        return redirect_to url
      end
      redirect_to :controller => :item, :action => :index
      return

    when OpenID::Consumer::FAILURE
      if response.identity_url
        flash[:notice] = "Verification of #{CGI::escape(response.identity_url)} failed."

      else
        flash[:notice] = 'Verification failed.'
      end

    when OpenID::CANCEL
      flash[:notice] = 'Verification cancelled.'

    else
      flash[:notice] = 'Unknown response from OpenID server.'
    end

    redirect_to :action => 'login'
  end

  def logout
    @session[:user_id] = nil
  end

  def welcome
  end

  private

  # Get the OpenID::Consumer object.
  def consumer
    store = ActiveRecordStore.new
    return OpenID::Consumer.new(session, store)

    # create the OpenID store for storing associations and nonces,
    # putting it in your app's db directory
    # store_dir = Pathname.new(RAILS_ROOT).join('db').join('openid-store')
    # store = OpenID::FilesystemStore.new(store_dir)
    # return OpenID::Consumer.new(@session, store)
  end

  # get the logged in user object
  def find_user
    return nil if session[:user_id].nil?
    User.find(session[:user_id])
  end

end
